package com.hxk.tx;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * spring声明式事务管理
 *      步骤：
 *          1、在给要使用事务的方法上加上@Transactional注解
 *          2、配置TransactionManager事务管理器
 *          3、使用@EnableTransactionManagement开启spring的事务管理功能
 */
@EnableTransactionManagement
@PropertySource("classpath:/db.properties")
@ComponentScan("com.hxk.tx")
@Configuration
public class MainConfigTx {

    @Value("${db.user}")
    private String user;

    @Value("${db.password}")
    private String password;

    @Value("${db.driverclass}")
    private String driverClass;

    /**
     * 配置数据源
     * @return
     * @throws Exception
     */
    @Bean
    public DataSource dataSource() throws Exception{
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC&useSSL=true");
        dataSource.setDriverClass(driverClass);
        dataSource.setUser(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 配置spring-jdbc模版类
     * @param dataSource 从ioc容器中获取dataSource并注入到方法中
     * @return
     */
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        //JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource());
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

    /**
     * 配置事务管理器
     * @return
     * @throws Exception
     */
    @Bean
    public TransactionManager transactionManager() throws Exception{
        return new DataSourceTransactionManager(dataSource());//这样也是从ioc容器中获取dataSource，不会重新创建
    }
}
